package com.example.httpdemo.retrofit

import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class RetrofitUtil {
    public fun getRetrofitUtil(): Retrofit {
        val retrofit = Retrofit.Builder()
            .baseUrl("http://172.27.184.11:9092/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        return retrofit;
    }

    /**
     * @author :WaiterXiaoYY
     * @description: 以下是协程模块代码，暂不使用，可忽略
     * @data :2020/12/20 10:29
     */
    suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if(body != null) {
                        continuation.resume(body)
                    }
                    else continuation.resumeWithException(RuntimeException("Body is Null!"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }
}